<?php
// +----------------------------------------------------------------------
// | 授权系统 - 授权管理控制器
// +----------------------------------------------------------------------
declare (strict_types=1);

namespace api\modules\admin\controllers\license;

use api\modules\admin\AuthController;
use api\utils\libs\CommonAction;
use common\models\system\License;
use common\services\system\LicenseService;
use yii\db\ActiveQuery;

/**
 * 授权管理控制器
 */
class LicenseController extends AuthController
{
    use CommonAction;
    
    protected string $model = License::class;
    protected bool $validate = true;
    
    protected function listQuery(ActiveQuery $query): ActiveQuery
    {
        return $query->with(['customer', 'product'])->orderBy(['id' => SORT_DESC]);
    }
    
    protected function loadBefore(array $data, string $type)
    {
        // 移除前端可能传递的自动生成字段
        if ($type === 'add') {
            unset($data['license_key'], $data['license_no']);
        }
        
        // 将前端传递的数组转换为JSON字符串（空数组保存为null）
        if (isset($data['domain']) && is_array($data['domain'])) {
            $data['domain'] = empty($data['domain']) ? null : json_encode($data['domain'], JSON_UNESCAPED_UNICODE);
        }
        if (isset($data['ip_whitelist']) && is_array($data['ip_whitelist'])) {
            $data['ip_whitelist'] = empty($data['ip_whitelist']) ? null : json_encode($data['ip_whitelist'], JSON_UNESCAPED_UNICODE);
        }
        
        return $data;
    }
    
    protected function saveBefore(\yii\db\ActiveRecord $model, string $type, array $oldData = []): string
    {
        if ($type === 'add') {
            // 自动生成授权码
            $model->license_key = $this->generateLicenseKey();
            
            // 自动生成授权编号
            $model->license_no = 'LIC-' . date('YmdHis') . '-' . rand(1000, 9999);
            
            // 设置默认状态
            if (!isset($model->status)) {
                $model->status = License::STATUS_NORMAL;
            }
        }
        
        return '';
    }
    
    protected function saveAfter(\yii\db\ActiveRecord $model, string $type, array $oldData = []): void
    {
        // 保存后生成加密的授权数据
        if (in_array($type, ['add', 'edit'])) {
            $this->generateEncryptedData($model);
        }
    }
    
    /**
     * 生成加密的授权数据
     */
    private function generateEncryptedData(License $model): void
    {
        $licenseData = [
            'license_key' => $model->license_key,
            'license_no' => $model->license_no,
            'customer_id' => $model->customer_id,
            'product_id' => $model->product_id,
            'license_type' => $model->license_type,
            'license_level' => $model->license_level,
            'start_date' => $model->start_date,
            'end_date' => $model->end_date,
            'max_users' => $model->max_users,
            'max_sites' => $model->max_sites,
            'domain' => $model->domain,
            'ip_whitelist' => $model->ip_whitelist,
            'status' => $model->status,
        ];
        
        // 使用base64编码（实际项目中应该使用更安全的加密方式）
        $encryptedData = base64_encode(json_encode($licenseData, JSON_UNESCAPED_UNICODE));
        
        // 更新加密数据
        License::updateAll(
            ['encrypted_data' => $encryptedData],
            ['id' => $model->id]
        );
    }
    
    /**
     * 生成授权码
     */
    private function generateLicenseKey(): string
    {
        do {
            // 生成32位授权码：8位前缀-8位随机-8位时间戳-8位随机
            $key = sprintf(
                '%s-%s-%s-%s',
                strtoupper(substr(md5(uniqid('', true)), 0, 8)),
                strtoupper(substr(md5((string)rand()), 0, 8)),
                strtoupper(substr(dechex(time()), 0, 8)),
                strtoupper(substr(md5((string)rand()), 0, 8))
            );
        } while (License::find()->where(['license_key' => $key])->exists());
        
        return $key;
    }
    
    protected function listAfter(array $list): array
    {
        // 格式化数据
        $formattedList = [];
        foreach ($list as $item) {
            $data = $item;
            $data['customer_name'] = $item['customer']['customer_name'] ?? '';
            $data['product_name'] = $item['product']['product_name'] ?? '';
            
            // 获取 License 模型来调用方法
            $license = License::findOne($item['id']);
            if ($license) {
                $data['license_type_text'] = $license->getLicenseTypeText();
                $data['status_text'] = $license->getStatusText();
                $data['remaining_days'] = $license->getRemainingDays();
                $data['is_expired'] = $license->isExpired();
            }
            
            $formattedList[] = $data;
        }
        return $formattedList;
    }
    
    protected function infoAfter(\yii\db\ActiveRecord $model): array
    {
        // 加载关联数据
        $model->refresh();
        $data = $model->toArray();
        
        // 添加关联信息
        $customer = $model->customer;
        $product = $model->product;
        
        $data['customer_name'] = $customer ? $customer->customer_name : '';
        $data['product_name'] = $product ? $product->product_name : '';
        $data['license_type_text'] = $model->getLicenseTypeText();
        $data['status_text'] = $model->getStatusText();
        $data['remaining_days'] = $model->getRemainingDays();
        $data['is_expired'] = $model->isExpired();
        
        // 解析JSON字段为数组
        $data['domain_list'] = $model->getDomainList();
        $data['ip_white_list'] = $model->getIpWhiteList();
        $data['feature_list'] = $model->getFeatureList();
        
        return $this->success('', ['info' => $data]);
    }
    
    /**
     * 续期授权
     */
    public function actionRenew()
    {
        $id = $this->request->post('id');
        $months = (int)$this->request->post('months', 12);
        
        if (LicenseService::renewLicense($id, $months)) {
            return $this->success('续期成功');
        }
        
        return $this->error('续期失败');
    }
    
    /**
     * 启用/禁用授权
     */
    public function actionToggleStatus()
    {
        $id = $this->request->post('id');
        $license = License::findOne($id);
        
        if (!$license) {
            return $this->error('授权不存在');
        }
        
        $license->status = $license->status == License::STATUS_NORMAL ? 
            License::STATUS_DISABLED : License::STATUS_NORMAL;
        
        if ($license->save(false)) {
            return $this->success('状态已更新');
        }
        
        return $this->error('操作失败');
    }
    
    /**
     * 生成授权文件
     */
    public function actionGenerateFile()
    {
        $id = $this->request->get('id');
        $license = License::findOne($id);
        
        if (!$license) {
            return $this->error('授权不存在');
        }
        
        // 返回加密的授权数据
        $fileContent = $license->encrypted_data;
        
        return $this->success('', [
            'filename' => 'license_' . $license->license_no . '.lic',
            'content' => $fileContent
        ]);
    }
}
